/*
 * @(#)LuceneHitsIterator.java	0.1 12/28/04
 *
 * Copyright 2004 Fabio Gasparetti. All rights reserved.
 */

package org.tabularium.text.se;

import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import org.apache.lucene.search.Hits;
import org.apache.lucene.document.*;
import org.apache.lucene.search.*;

/**
 *
 */
public class LuceneHitsIterator implements HitsIterator {
  protected Hits hits;
  protected Searcher searcher = null;
  protected int currentHit = 0;
  protected double currentScore = 0d;
  protected Document currentDoc = null;
  protected int numHits;
  // run the garbwage collector after N iteration
  // public static final int GCINTERVAL = 100;


  LuceneHitsIterator(Hits hits, Searcher searcher) {
    this.hits = hits;
    this.searcher = searcher;
    numHits = hits.length();
  }

  public boolean hasNext() {
    return currentHit < numHits;
  }

  /**
   * Return the next Document object in the hit list.
   * Once retrieved, it is possible to obtain the fields.
   */
  public Object next() {
    if (currentHit < numHits) {
      try {
        currentDoc = hits.doc(currentHit);
        currentScore = hits.score(currentHit);
        currentHit++;
      } catch (Exception ex) {
        currentHit = numHits;
        currentDoc = null;
        System.err.println(ex.toString());
        return null;
      }
      //currentHit++;
    } else {
      try {
        // closes IndexReader
        interrupt();
      } catch (Exception ex) { }
    }
    return currentDoc;
  }

  
  public void remove() {
    // not implemented
  }

  public String getId() {
    return currentDoc != null ? currentDoc.get("idse") : null;
  }

  public double getScore() {
    return currentDoc != null ? currentScore : -1d;
  }

  /**
   * Invoke this method to close the IndexReader associated with the searcher.
   */
  public void interrupt() throws IOException {
    if (searcher != null) {
      searcher.close();
      searcher = null;
    }
  }

  protected void finalize() throws Throwable {
    interrupt();
  }
}
